package com.net.xpay.common.util;

import java.security.*;
import java.util.Base64;

public class RSA2Util {

    public static String[] genRSA2() throws NoSuchAlgorithmException {
        String[] keys = new String[2];

        //初始化KeyPairGenerator
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048, new SecureRandom());

        // 生成一对公钥私钥
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // 编码公钥
        byte[] publicKeyEncoded = publicKey.getEncoded();
        String publicKeyBase64 = Base64.getEncoder().encodeToString(publicKeyEncoded);
        keys[0] = publicKeyBase64;

        // 编码私钥为PKCS8格式
        byte[] privateKeyEncoded = privateKey.getEncoded();
        String privateKeyBase64 = Base64.getEncoder().encodeToString(privateKeyEncoded);
        keys[1] = privateKeyBase64;

        return keys;
    }
}
